//初始化及注册事件响应代码
//
$(function(){
	$('#detail').hide();
	//初始化事件日期
	$('#nowDate').textbox('setValue',new Date().format("yyyy-MM-dd"));
	//初始化事件ID号
	var eventId=createEventId();
	$('#eventId3').attr('value',eventId);
	$('#eventId2').attr('value',eventId);
	$('#eventId1').html(eventId);
	$('#eventId').attr('value',eventId);
	
	$(window).bind("beforeunload",function(){
		$.ajax({
			url:'Login_out',
			type:'post'
		})
		//return true;
	});
});

function find() {
	var victimeType = $("#victimeType").combobox('getValue');
	var keyword = $('#keyword').val();
	var findBy = $('#findBy').combobox('getValue');
	if (victimeType == '学生') {
		$("#info").datagrid({
			url : 'FastCheckIn_findStudent?keyword='+keyword+"&findBy="+findBy,
			title : '所有符合人员',
			loadMsg : '加载中...',
			iconCls : 'icon-search',
			width : '100%',
			height : 360,
			toolbar : '#toolbar',
			columns : [ [ {
				field : 'STUDENTID',
				title : '学号',
				width : 160,
				align : 'center',
				sortable : 'true'
			}, {
				field : 'STUDENTNAME',
				title : '姓名',
				width : 160,
				align : 'center',
				sortable : 'true'
			}, {
				field : 'DEPARTMENTNAME',
				title : '学院',
				width : 80,
				align : 'center',
				sortable : 'true'
			}, {
				field : 'CLASSNAME',
				title : '班级',
				width : 200,
				align : 'center',
				sortable : 'true'
			} ] ],
			singleSelect : true,
			collapsible:true,
			pageSize : 10,
			pageList : [ 10, 20, 30 ],
			pageNumber : 1,
			sortName : 'STUDENTID',
			sortOrder : 'desc',
			pagination : true,//分页控件 
			rownumbers : true,//行号  
			//双击执行的操作
			onDblClickRow : function() {
				showDetail();
			}
		});
	} else {
		$("#info").datagrid({
			url : 'FastCheckIn_findEmp?keyword='+keyword,
			title : '所有符合人员',
			loadMsg : '加载中...',
			iconCls : 'icon-search',
			width : '100%',
			height : 360,
			toolbar : '#toolbar',
			columns : [ [ {
				field : 'DEPARTMENTNAME',
				title : '工作单位',
				width : 160,
				align : 'center',
				sortable : 'true'
			}, {
				field : 'EMPNAME',
				title : '姓名',
				width : 160,
				align : 'center',
				sortable : 'true'
			}] ],
			singleSelect : true,
			collapsible:true,
			pageSize : 10,
			pageList : [ 10, 20, 30 ],
			pageNumber : 1,
			sortName : 'DEPARTMENTNAME',
			sortOrder : 'desc',
			pagination : true,//分页控件 
			rownumbers : true,//行号  
			//双击执行的操作
			onDblClickRow : function() {
				showDetail();
			}
		});
	}
	$('#parent').show();
}
//
//
function showDetail(){
	$("#parent").hide("");
	$('#detail').show();
	var victimeType = $('#victimeType').combobox('getValue');
	var rows=$("#info").datagrid('getSelected');
	if(victimeType == '学生'){
		$('#student').show();
		$('#teacher').hide();
		$.ajax({
			url:'FastCheckIn_queryStudent?keyword='+rows.STUDENTID,
			type:'get',
			dataType:'json',
			success: function(data){
				$('#stud_academy').textbox('setValue',data[0].DEPARTMENTNAME);
				$('#stud_major').textbox('setValue',data[0].MAJOR);
				$('#className').textbox('setValue',data[0].CLASSNAME);
				$('#gender').textbox('setValue',data[0].GENDER);
				$('#stud_name').textbox('setValue',data[0].STUDENTNAME);
				$('#stud_major').textbox('setValue',data[0].MAJOR);
				$('#stud_id').textbox('setValue',data[0].STUDENTID);
				$('#stu_room').textbox('setValue',data[0].STUROOM);
				$('#classMonitor').textbox('setValue',data[0].CLASSMONITORNAME);
				$('#classDirector').textbox('setValue',data[0].CLASSDIRECTORNAME);
				$('#directorPhoneNumber').textbox('setValue',data[0].CLASSDIRECTORPHONE);
				$('#grade').textbox('setValue',data[0].CLASSID.substring(0,2)+'级');
			}
		});
	}else if(victimeType == '教职工'){
		$('#student').hide();
		$('#teacher').show();
		$.ajax({
			url:'FastCheckIn_queryEmp?keyword='+rows.EMPNAME,
			type:'get',
			dataType:'json',
			success:function(data){
				//alert(JSON.stringify(data));
				$('#teac_academy').textbox('setValue',data[0].DEPARTMENTNAME);
				$('#teac_building').textbox('setValue',data[0].BUILDING);
				$('#teac_room').textbox('setValue',data[0].ROOM);
				$('#departmentLeader').textbox('setValue',data[0].USERNAME);
				$('#leaderPhoneNumber').textbox('setValue',data[0].PHONE);
			}
		});
	}
	
}

/**
 * 检测学号是否合法
 */
function checkStuNum(){
	
	var r=$('#reporterId').val();
	var p =/[^\d]/;
	var d=r.replace(p,"");
	$('#reporterId').val(d);
}
/**
 * 检测电话格式
 */
function checkPhoneNum(){
	var r=$('#reporterPhoneNum').val();
	var p =/[^\d-]/;
	var d=r.replace(p,"");
	$('#reporterPhoneNum').val(d);
}

/**
 * 时间对象的格式化
 */
Date.prototype.format = function(format) {
	/*
	 * format="yyyy-MM-dd hh:mm:ss";
	 */
	var o = {
		"M+" : this.getMonth() + 1,
		"d+" : this.getDate(),
		"h+" : this.getHours(),
		"m+" : this.getMinutes(),
		"s+" : this.getSeconds(),
		"q+" : Math.floor((this.getMonth() + 3) / 3),
		"S" : this.getMilliseconds()
	}

	if (/(y+)/.test(format)) {
		format = format.replace(RegExp.$1, (this.getFullYear() + "")
				.substr(4 - RegExp.$1.length));
	}

	for ( var k in o) {
		if (new RegExp("(" + k + ")").test(format)) {
			format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k]
					: ("00" + o[k]).substr(("" + o[k]).length));
		}
	}
	return format;
}
//随机产生
function _getRandomString(len) {  
    len = len || 32;  
    var $chars = 'abcdefhijkmnprstwxyz'; // 默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1  
    var maxPos = $chars.length;  
    var pwd = '';  
    for (i = 0; i < len; i++) {  
        pwd += $chars.charAt(Math.floor(Math.random() * maxPos));  
    }  
    return pwd;  
}  

//产生事件号ID
function createEventId(){
	var time = new Date();
	return time.format("yyyyMMddhhmm")+_getRandomString(8);
}

// 保存事件处理
function saveEvent() {
	var victimeType = $('#victimeType').combobox('getValue');
	var reporterName="";
	var reporterTeacherName="";
	if(victimeType == '学生'){
		reporterName = $('#stud_name').val();
	}else{
		reporterTeacherName = $('#keyword').val();
	}
	var relation='本人';
	var formdata='victimeType='+victimeType+"&reporterName="+reporterName+"&reporterTeacherName="+reporterTeacherName;
	formdata=formdata+"&relation="+relation;
	formdata=formdata+"&"+$("#victimeForm").serialize();
	formdata=formdata+"&"+$("#eventForm").serialize();
//	alert(formdata);
	$.ajax({
		url:'Event2_add',
		type:'Post',
		data:formdata,
		datatype:'json',
		success:function(data){
//			alert(JSON.stringify(data));
//			alert("保存事件成功");
/*			var obj = eval('(' + data + ')');
			alert(JSON.stringify(obj));
			closeMsg(0);
			if (!obj.RESULT) {
				showMsg("保存事件失败", 0);
			} else {
				showMsg("保存事件成功", 1);
			}*/
			if (!data.RESULT) {
				showMsg("保存事件失败", 0);
			} else {
				showMsg("保存事件成功", 1);
			}
		}
	});
	
//	return false;
/*	if($('#eventForm').form('validate')){
		ajaxLoading('保存事件中...');
		$('#eventForm').form('submit', {
			url : 'Event_add',
			onSubmit : function() {
				// alert($('#eventForm').serialize());
				return $(this).form('validate');
			},
			success : function(data) {
				var obj = eval('(' + data + ')');
				closeMsg(0);
				if (!obj.RESULT) {
					showMsg("保存事件失败", 0);
				} else {
					showMsg("保存事件成功", 1);
				}
			}
		});
	}*/
}

// 发送邮件给报导人
function sendEmail() {
		if($('#eventForm').form('validate')){
				ajaxLoading("邮件发送中...");
				$('#eventForm').form('submit', {
					url : 'Mail',
					success : function(data) {
						closeMsg(0);
						var obj = eval('(' + data + ')');
						if (!obj.RESULT) {
							showMsg("发送邮件失败，请重试", 0);
						} else {
							showMsg("发送邮件成功", 1);
						}
					}
				});
		}
}

// 发送短信初始化
function sendSMS() {
	var name="";
	var addr="";
	var text="";
	if($("#informAdminDepartmentLeader").is(":checked")){
		name = name + $("#adminDepartmentLeader").combobox('getValue') + ",";
		addr = addr + $("#adminDepartmentLeaderPhone").val() + ",";
	}
	if($("#informCooperate").is(":checked")){
		name = name + $("#cooperateDepartmentLeader").combobox('getValue') + ",";
		addr = addr + $("#cooperateDepartmentLeaderPhone").val() + ",";
	}
	if($("#informClassDirector").is(":checked")){
		name = name + $("#classDirector").val() + ",";
		addr = addr + $("#directorPhoneNumber").val() + ",";
	}
	if($("#informExecutor").is(":checked")){
		name = name + $("#executor").val() + ",";
		addr = addr + $("#executorPhone").val() + ",";
	}
	addr = addr + $("#informOthers").val()+",";
	var victimeType = $("#victimeType").combobox('getValue');
	//精简短信内容
	//var text = $("#eventType").combobox('getValue')+"案件发生," + "案发日期为:"+$("#nowDate").val()+"。";
	//text = text + "当事人为" + victimeType +"，性别为："+$("#gender").textbox('getValue');
	//text = text + "，系";
	var text="";
	if(victimeType == '学生'){
		text = text + $("#className").textbox('getValue') + "，" + $("#stud_name").textbox('getValue')+"报案。";
		text = text + "地址：" + $("#stu_room").val()+"，电话："+$("#contactPhone").val()+"，性别："+$("#gender").textbox('getValue')+"。";
		text = text +"案件内容：" +$("#eventContent").val() + "。110指挥中心。"
	} else if (victimeType='教职工'){
		text = text + $("#teac_academy").textbox('getValue')+"，" + $("#keyword").textbox('getValue') + "报案。";
		text = text + "地址："+$("#teac_building").val()+$("#teac_room").val();
		text = text + "，电话："+$("#reporterTeacherContactPhone").val()+"。";
		text = text + "案件内容：" +$("#eventContent").val() + "。110指挥中心。"
	}
/*	if($('#department').val()==''){
		showMsg('请先选择主管部门',0);
	}else if($('#username').val()==''){
		showMsg('请先选择部门领导',0);
	}else*/
	
	$('#fm').form('load', {
			"name" : name,
			"addr" : addr,
			"text" : text
	});
	$('#sendSMS').dialog('open');
	$("#smstext").html($("#smscontent").val());
	
}

// 发送短信操作
function doSendSMS() {
	var eventId = $("#eventId").val();
	$("#smscontent").val($("#smstext").val());
	//alert($('#fm').form('validate'));
	//alert($('#fm').serialize());
	if ($('#fm').form('validate')) {
		ajaxLoading("正在发送中...");
		$('#sendSMS').dialog('close');
		$.ajax({
			url : 'Sms',
			type : 'POST',
			data:$('#fm').serialize()+"&eventId="+eventId,
			success : function(data) {
//				alert("result" + data.RESULT);
/*				if (!data.RESULT) {
					closeMsg(1);
					$.messager.alert("操作提示",
							"<font size=\"4\">短信发送失败，请重试</font>", "error",
							function() {
								$('#sendSMS').dialog('open');
							});
				} else {
					closeMsg(1);
					showMsg("发送短信成功", 1);
				}*/
				closeMsg(1);
				alert("共发送"+data.total+"条短信,"+"成功"+data.success+"条,"+"失败"+data.failed+"条。");
			},
			error : function() {
				closeMsg(1);
				$.messager.alert("操作提示", "<font size=\"4\">短信发送失败，请重试</font>",
						"error", function() {
							$('#sendSMS').dialog('open');
						});
			}
		});
	}
}

//============================检测是否为音频或者图片=====================
function checkIsImage(){
	var t = /\.(jpg|jpeg|png)$/;
	var img = $('#imageFile').val();
	if(img==''){
		showMsg('请选择图片上传',0);
		return false;
	}
	if(!t.test(img)){
		showMsg('您选择的不是图片，请选择图片(jpg,jpeg,png)',0);
		return false;
	}
	return true;
}

function checkIsAudio(){
	var t = /\.(mp3|wav)$/;
	var audio = $('#audioFile').val();
	if(audio==''){
		showMsg('请选择录音上传',0);
		return false;
	}
	if(!t.test(audio)){
		showMsg('您选择的不是录音，请选择录音(mp3,wav)',0);
		return false;
	}
	return true;
}
//===========================结束==============================

//根据是否支持浏览器 显示不同的播放器
function checkPlayer(){
		 if (window.applicationCache) {
	         return true;
	     } else {
	         return false;
	     }
}

//播放录音
function audioPlayer(eId,aId){
	if(checkPlayer()){
		//html5播放器
		$('#statrAudio').html("<audio src=\"Audio_get?eventId="+eId+"&&id="+aId+"\" controls=\"controls\"></audio><iframe id=\"tmp_downloadhelper_iframe\" style=\"display: none;\"></iframe>");
	}else{
		//微软播放器
		$('#statrAudio').html("<embed src=\"Audio_get?eventId="+eId+"&&id="+aId+"\" height=\"50px\" width=\"300px\"pluginspage=\"http://www.microsoft.com/isapi/redir.dll?prd=windows&sbp=mediaplayer&ar=media&sba=plugin&\" type=\"application/x-mplayer2\" border=\"0\" width=\"100%\" height=\"40\" showcontrols=\"1\" showaudiocontrols=\"1\" showstatusbar=\"1\" autostart=\"0\" loop=\"0\" enablecontextmenu=\"1\"></embed>");
	}
	$('#audioPlayer').dialog('open');
}

//刷新图片页面
function reloadImage(eId){
	$.get("Image_exist?eventId="+eId,function(json){
		var str='';
		if(json!=null){
			$.each(json,function(i,n){
				str = str + "<a target=\"_Blank\"href=\"Image_get?eventId="+eId+"&&id="+n.IMAGEID+"\" title=\"点击查看图片\">"+n.IMAGENAME+"</a><a onclick=\"deleteImage('"+eId+"','"+n.IMAGEID+"')\"><img title=\"点击删除\" src=\"images/delete.gif\"></a>";
			});
			$('#imageBox').html(str);
		}
	},'json');
}

//刷新录音列表
function reloadAudio(eId){
	$.get("Audio_exist?eventId="+eId,function(json){
		var str='';
		if(json!=null){
			$.each(json,function(i,n){
				str = str + "<a onclick=\"audioPlayer('"+eId+"','"+n.AUDIOID+"')\" title=\"点击播放录音\">"+n.AUDIONAME+"</a><a onclick=\"deleteAudio('"+eId+"','"+n.AUDIOID+"')\"><img title=\"点击删除\" src=\"images/delete.gif\"></a>";
			});
			$('#audioBox').html(str);
			//alert('reloadAudio');
			//alert($('#audioBox').html());
		}
	},'json');
}

//上传录音
function uploadAudio(){
	if(checkIsAudio()){
		$('#uploadAudioLoading').html("<img src=\"images/upload.gif\" width=\"100\" height=\"15\"/>");
	$('#audioForm').form('submit',{
		url : 'Audio_add',
		success : function(data) {
			var obj = eval('(' + data + ')');
			if (!obj.RESULT) {
				$('#uploadAudioLoading').html("<img src=\"images/error.png\"/>&nbsp;<font color=red>上传失败！</font>");
			} else {
				$('#uploadAudioLoading').html("<img src=\"images/success.gif\"/>&nbsp;<font color=red>上传成功！</font>");
				reloadAudio($('#eventId2').val());
			}
			setTimeout(function(){
				$('#uploadAudioLoading').html('');
			},3000);
		}
	});
	}
};

//上传图片
function uploadImage(){
	if(checkIsImage()){
		$('#uploadImageLoading').html("<img src=\"images/upload.gif\" width=\"100\" height=\"15\"/>");
		$('#imageForm').form('submit',{
		url : 'Image_add',
		success : function(data) {
			var obj = eval('(' + data + ')');
			if (!obj.RESULT) {
				$('#uploadImageLoading').html("<img src=\"images/error.png\"/>&nbsp;<font color=red>上传失败！</font>");
			} else {
				$('#uploadImageLoading').html("<img src=\"images/success.gif\"/>&nbsp;<font color=red>上传成功！</font>");
				reloadImage($('#eventId3').val());
			}
			setTimeout(function(){
				$('#uploadImageLoading').html('');
			},3000);
		}
	});
	}
}

//删除图片
function deleteImage(eid,imgId){
	$.messager.confirm('友情提示', '您确定要删除吗?',function(data){
		if(data){
			$.ajax({
				url:'Image_delete',
				type:'GET',
				data:'id='+imgId+'&&eventId='+eid,
				dataType:'json',
				beforeSend:function(){
					$('#uploadImageLoading').html("<img src=\"images/deleteLoading.gif\"/>&nbsp;<font color=red>删除中...</font>");
				},
				success:function(json){
					if(json.RESULT){
						$('#uploadImageLoading').html("<img src=\"images/success.gif\"/>&nbsp;<font color=red>删除成功！</font>");
						reloadImage($('#eventId2').val());
					}else{
						$('#uploadImageLoading').html("<img src=\"images/error.png\"/>&nbsp;<font color=red>删除失败！</font>");
					}
					setTimeout(function(){
						$('#uploadImageLoading').html('');
					},3000);
				},
				error:function(){
					$('#uploadImageLoading').html("<img src=\"images/error.png\"/>&nbsp;<font color=red>删除失败！</font>");
					setTimeout(function(){
						$('#uploadImageLoading').html('');
					},3000);
				}
			});
		}
	})
}

//删除录音
function deleteAudio(eid,aId){
	$.messager.confirm('友情提示', '您确定要删除吗?',function(data){
		if(data){
			$.ajax({
				url:'Audio_delete',
				type:'GET',
				data:'id='+aId+'&&eventId='+eid,
				dataType:'json',
				beforeSend:function(){
					$('#uploadAudioLoading').html("<img src=\"images/deleteLoading.gif\"/>&nbsp;<font color=red>删除中...</font>");
				},
				success:function(json){
					if(json.RESULT){
						$('#uploadAudioLoading').html("<img src=\"images/success.gif\"/>&nbsp;<font color=red>删除成功！</font>");
						reloadAudio($('#eventId2').val());
					}else{
						$('#uploadAudioLoading').html("<img src=\"images/error.png\"/>&nbsp;<font color=red>删除失败！</font>");
					}
					setTimeout(function(){
						$('#uploadAudioLoading').html('');
					},3000);
				},
				error:function(){
					$('#uploadAudioLoading').html("<img src=\"images/error.png\"/>&nbsp;<font color=red>删除失败！</font>");
					setTimeout(function(){
						$('#uploadAudioLoading').html('');
					},3000);
				}
			});
		}
	})
}

//打印事件
function printEvent(){
	var reporterName = "";
	var reporterTeacherName="";
	var relation="本人";
	var victimeType=$("#victimeType").combobox('getValue');
	var findBy = $("#findBy").combobox('getValue');
	var keyword = $("#keyword").textbox('getValue');
	if(victimeType == '教职工')
		reporterTeacherName = keyword;
	else{
		if(findBy == '姓名')
			reporterName = keyword;
	}
	var formdata = ""+"reporterName="+reporterName+"&relation="+relation+"&victimeType="+victimeType;
	formdata = formdata + "&reporterTeacherName="+reporterTeacherName;
	if($('#eventForm').form('validate')){
		formdata=formdata+"&"+$("#victimeForm").serialize();
		formdata=formdata+"&"+$("#eventForm").serialize();
		$.messager.confirm('友情提示', '您真的要打印吗？',function(data){
			if(data){
				window.open("Event2_print?"+formdata);
			}
		});
	}else{
		showMsg("打印之前，先填写完整事件基本内容",0);
	}
}

//防止session过期初始化
window.onload=function(){
	window.setInterval('avoidSessionExpire()',5*60*1000);
}

//防止session过期操作
function avoidSessionExpire(){
	$.get('Login_sessionExpire?rd='+new Date().valueOf(),function(data){
		//不做处理
	},'json');
}